import logging
from rest_framework import views
from rest_framework import viewsets
from rest_framework import mixins
from rest_framework import permissions
from rest_framework import status
from rest_framework.response import Response
from rest_framework.authentication import SessionAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from .models import LdapBaseConf
from .serializers import LdapConfSrializer
from .utils.LdapAuth import AuthBaseLdap

CUSTOM_ERROR = logging.getLogger('apps.views')


class LdapViewSet(viewsets.GenericViewSet,
                  mixins.ListModelMixin,
                  mixins.CreateModelMixin,
                  mixins.UpdateModelMixin):
    # ldap设置
    queryset = LdapBaseConf.objects.all()
    permission_classes = (permissions.IsAuthenticated,)
    authentication_classes = (SessionAuthentication, JSONWebTokenAuthentication)
    serializer_class = LdapConfSrializer


class LdapConnectTest(views.APIView):
    # 测试ldap连接
    permission_classes = (permissions.IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def get(self, request, *args, **kwargs):
        port = self.request.query_params['port']
        host = self.request.query_params['url']
        admin_dn = self.request.query_params['dn']
        password = self.request.query_params['password']

        ldapAuth = AuthBaseLdap()
        ldap_test = ldapAuth.ConnectLdap(host, port, admin_dn, password)
        return Response(status=status.HTTP_200_OK, data=ldap_test)



